<?php

/**
 * User: day
 * Date: 2018/10/9
 * Time: 16:48
 * Desc: 用户第三方游戏数据统计
 */

namespace App\Console\Commands\ReportData;

use App\Models\Agent;
use App\Models\User;
use common\enum\OrderEnum;
use Illuminate\Support\Facades\DB;
use common\utils\RedisKeys;
use App\Models\Order;
use App\Models\ReportPartnerGame as ReportPartnerGameModel;

class ReportPartnerGame extends BaseReport
{

    protected $signature = self::PREFIX . 'report_partner_game {--reload=} {--begin=} {--end=} {--command=}';

    protected $description = "用户第三方游戏数据统计";

    public $reportName = "ReportPartnerGame";
    /**
     * 获取需要处理的数据
     */
    public function getData($beginTime, $endTime)
    {
        try{
            //先统计已结算的统计 ============================================================================
            $sumData = Order::select([
                DB::raw("DATE_FORMAT(reckon_time, '%Y-%m-%d') as date"),
                'hall_id',
                'user_id',
                'username',
                'partner_id', // '对应 partner 表的 id',
                'partner_name', // '对应 partner 表的 name',
                'game_type', // '游戏注单类型, 1:电子，2:视讯，3:体育 4:电竞 5:彩票 6:棋牌',
                DB::raw('COUNT(1) as validbet_times'), // '投注笔数',
                DB::raw('SUM(validbet) as validbet'), // '当天已结算注单的 有效投注 单位厘',
                DB::raw('SUM(prize) as prize'), // '当天已结算注单的 派彩金额 单位厘',
                DB::raw('SUM(profit) as profit'), // '当天已结算注单的 输赢 单位厘',
                DB::raw('SUM(bonus_amount) as bonus_amount'), // '当天已结算注单的 奖池奖金 单位厘',
                DB::raw('SUM(contribute_amount) as contribute_amount'), // '当天已结算注单的 奖池贡献 单位厘',
            ])
                ->whereBetween('reckon_time', [$beginTime, $endTime])
                ->where('status', '=', OrderEnum::OPEN)//只取已结算注单
                ->groupBy('date', 'user_id', 'partner_id', 'game_type')
                ->get()->toArray();
            $this->dealData($sumData);
        }catch (\Throwable $e){
            $this->info($e->getMessage());
        }

        //统计总笔数和总投注使用（不区分订单状态）=========================================================
        return Order::select([
            DB::raw("DATE_FORMAT(reckon_time, '%Y-%m-%d') as date"),
            'hall_id',
            'user_id',
            'username',
            'partner_id', // '对应 partner 表的 id',
            'partner_name', // '对应 partner 表的 name',
            'game_type', // '游戏注单类型, 1:电子，2:视讯，3:体育 4:电竞 5:彩票 6:棋牌',
            DB::raw('COUNT(1) as bet_times'), // '投注笔数',
            DB::raw('SUM(bet_amount) as bet_amount'), // '当天已结算注单的 投注金额 单位厘',
        ])
            ->whereBetween('reckon_time', [$beginTime, $endTime])
            ->groupBy('date', 'user_id', 'partner_id', 'game_type')
            ->get()->toArray();
    }

    /**
     * 处理数据
     */
    public function dealData($data)
    {
        foreach ($data as $value) {
            $userId =  $value['user_id'];
            //获取代理信息
            $userInfo = User::select(['agent_id', 'agent_name'])->where(['id' =>$userId])->first();
            if($userInfo){
                $value['agent_id'] = $userInfo->agent_id;
                $value['agent_name'] = $userInfo->agent_name;
            }
                // update or insert
            $model = ReportPartnerGameModel::where([
                'hall_id' => $value['hall_id'],
                'date' => $value['date'],
                'user_id' => $value['user_id'],
                'partner_id' => $value['partner_id'],
                'game_type' => $value['game_type'],
            ])->first();
            if (empty($model)) {
                $model = new ReportPartnerGameModel($value);
            }else{
                $model->update($value);
            }
            $res = $model->save();
            if (!$res) {
                $this->error("{$this->processName} 保存数据失败: " . json_encode($model->getErrors(), JSON_UNESCAPED_UNICODE));
                return false;
            }
        }
        //exit;
        return true;
    }
}